package com.sample.kokou;

import java.sql.SQLException;

import com.j256.ormlite.android.apptools.OrmLiteBaseListActivity;
import com.j256.ormlite.dao.Dao;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.TextView;

public class DeletePerson implements OnItemLongClickListener {
    private OrmLiteBaseListActivity<SampleDBHelper> act;

    DeletePerson(OrmLiteBaseListActivity<SampleDBHelper> act) {
        this.act = act;
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        TextView nameView = GenericUtil.getView(view, R.id.name);
        confirmDeleteDialog(parent.getContext(), (int)id, nameView.getText().toString()).show();
        return true;
    }

    private AlertDialog confirmDeleteDialog(Context context, final int id, String name) {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle(R.string.confirm);
        builder.setMessage(String.format(act.getResources().getString(R.string.confirm_deletion), name));
        builder.setPositiveButton(android.R.string.yes, new DoDelete(id));
        builder.setNegativeButton(android.R.string.no, null);
        return builder.create();
    }

    private class DoDelete implements OnClickListener {
        private int id;

        DoDelete(int id) { this.id = id; }

        @Override
        public void onClick(DialogInterface dialog, int which) {
            try {
                Dao<Person, Integer> dao = act.getHelper().getDao(Person.class);
                Person person = dao.queryForId(id);
                dao.delete(person);
                act.setListAdapter(new PersonListAdapter(act, dao.queryForAll()));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
